using System.Data.Common;
using System.IO;
using DbVisualizer.DbConnection;
using DbVisualizer.DbConnection.UI;
using Microsoft.VisualStudio.DebuggerVisualizers;

[assembly: System.Diagnostics.DebuggerVisualizer(
    typeof(DbConnectionVisualizer), 
    typeof(DebugeeObjectSource), 
    Target = typeof(DbConnection), 
    Description = "BinaryRefinery DBConnection Visualizer")]

namespace DbVisualizer.DbConnection
{
    public class DbConnectionVisualizer : DialogDebuggerVisualizer, IDbConnectionProxy
    {
        private IVisualizerObjectProvider visualizerObjectProvider;

        string IDbConnectionProxy.ConnectionString
        {
            get
            {
                var connString = (string)visualizerObjectProvider.GetObject();

                return connString;
            }
        }

        QueryResult IDbConnectionProxy.RunQuery(string sql)
        {
            var sqlStream = GetStreamFromString(sql);
            visualizerObjectProvider.TransferData(sqlStream);

            var result = (QueryResult)visualizerObjectProvider.GetObject();

            return result;
        }

        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            visualizerObjectProvider = objectProvider;
            var ui = new QueryForm(this);

            windowService.ShowDialog(ui);
        }

        private static Stream GetStreamFromString(string input)
        {
            var outputStream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(input));

            return outputStream;
        }
    }
}